<?php
/**
 * Created by PhpStorm.
 * User: jifee8505
 * Date: 2018/4/2
 * Time: 上午11:04
 */

namespace common\components;

use Yii;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class RabbitMQ
{
    /**
     * @var AMQPStreamConnection
     */
    private static $connection;

    public static function getConnection()
    {
        if (empty(self::$connection)) {
            $conf = Yii::$app->rabbitmq;
            self::$connection = new AMQPStreamConnection($conf->host, $conf->port, $conf->username, $conf->password);
        }
        return self::$connection;
    }

    public static function getChannel()
    {
        return self::$connection->channel();
    }

    public static function sendP2PMsg($queue, $msg)
    {
        $connection = self::getConnection();
        $rabbitmq_channel = self::getChannel();
        $rabbitmq_channel->queue_declare($queue, false, true, false, false, true);

        $msg = new AMQPMessage($msg, array('delivery_mode' => 2));
        $rabbitmq_channel->basic_publish($msg, '', $queue);
        $rabbitmq_channel->close();
        $connection->close();
    }

}